﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using ASPItalia.ModelVirtualCasting.Silverlight.ModelVirtualCastingServices;
using System.Collections.ObjectModel;
using System.ServiceModel;

namespace ASPItalia.ModelVirtualCasting.Silverlight.Models
{
  public class DataModelsServiceModel : IDataModelsModel
  {
    ModelsManagerClient modelsClient;
    public event EventHandler<AllModelsLoadedEventArgs> AllModelsLoadCompleted;
    public event EventHandler<DataLoadingErrorEventArgs> DataLoadingError;

    public DataModelsServiceModel()
    {
      modelsClient = new ModelsManagerClient();
      modelsClient.GetAllModelsCompleted += new EventHandler<GetAllModelsCompletedEventArgs>(modelsClient_GetAllModelsCompleted);
    }

    public void GetAllModels()
    {
      modelsClient.GetAllModelsAsync(null);
    }

    void modelsClient_GetAllModelsCompleted(object sender, GetAllModelsCompletedEventArgs e)
    {
      if (e.Result != null && e.Error == null)
      {
        GetAllModelsResponse data = e.Result;
        ObservableCollection<Model> temp = data.Models;
        ((ICommunicationObject)modelsClient).Close();
        OnAllModelsLoadCompleted(data.Models);
      }
      else
      {
        OnDataLoadingError(e.Error);
      }
    }

    public void OnAllModelsLoadCompleted(ObservableCollection<Model> result)
    {
      if (AllModelsLoadCompleted != null)
        AllModelsLoadCompleted(this, new AllModelsLoadedEventArgs(result));
    }

    public void OnDataLoadingError(Exception ex)
    {
      if (DataLoadingError != null)
        DataLoadingError(this, new DataLoadingErrorEventArgs(ex));
    }
  }
}
